@tool
class_name HealthBar
extends Range

@export var progress_color : Color
@export var background_color : Color = Color.BLACK
@export var deferred_color : Color = Color.WHITE
@export var threshold : float = 0

var _deferred_value : float
var _change_timer : float

func _ready() -> void:
	_deferred_value = value
	queue_redraw()

func _value_changed(new_value: float) -> void:
	if _change_timer > 0 or _deferred_value - new_value > threshold * max_value:
		_change_timer = 0
		set_process(true)
	else:
		_deferred_value = new_value
	
	queue_redraw()

func _process(delta: float) -> void:
	if _change_timer > 0.0:
		_change_timer -= delta
		return
	
	if _deferred_value > value:
		if is_equal_approx(_deferred_value, value):
			_deferred_value = value
			set_process(false)
		else:
			_deferred_value = lerp(_deferred_value, value, 0.2)
		queue_redraw()

func _draw() -> void:
	var rect = get_rect()
	rect.position = Vector2.ZERO

	var deferred_rect = rect
	deferred_rect.size.y *= _deferred_value / max_value
	deferred_rect.position.y = rect.size.y - deferred_rect.size.y

	var fg_rect = rect
	fg_rect.size.y *= value / max_value
	fg_rect.position.y = rect.size.y - fg_rect.size.y

	draw_rect(rect, background_color)
	draw_rect(deferred_rect, deferred_color)
	draw_rect(fg_rect, progress_color)
